<template>
  <view class="container">
    <scroll-view 
      class="content-scroll"
      scroll-y
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh()"
      @scrolltolower="loadMore()"
    >
      <!-- 顶部搜索 -->
      <view class="search-section">
        <view class="search-box">
          <image src="/static/home/search.png" class="search-icon" />
          <input
            v-model="searchKeyword"
            placeholder="搜索农产品"
            class="search-input"
            confirm-type="search"
            @confirm="handleSearch"
          />
          <text 
            v-if="searchKeyword" 
            class="clear-btn"
            @tap.stop="clearSearch"
          >×</text>
        </view>
        <text 
          class="search-btn"
          :class="{ active: searchKeyword }"
          @tap="handleSearch"
        >搜索</text>
      </view>

      <!-- 轮播图 -->
      <swiper class="banner" circular autoplay interval="3000" indicator-dots>
        <swiper-item v-for="banner in bannerList" :key="banner.id">
          <image :src="banner?.image" mode="aspectFill" class="banner-image" />
        </swiper-item>
      </swiper>

      <!-- 优惠券秒杀区域 -->
      <view class="coupon-section" v-if="seckillCoupons.length > 0">
        <view class="coupon-container">
          <view 
            class="compact-coupon-card"
            :class="seckillCoupons[0]?.type === 'fixed' ? 'fixed-bg' : 'percent-bg'"
            @tap="showCouponPopup"
          >
            <view class="coupon-left">
              <view class="coupon-amount">
                <text v-if="seckillCoupons[0]?.type === 'fixed'">¥<text class="amount-num">{{seckillCoupons[0]?.discountAmount || 0}}</text></text>
                <text v-else><text class="amount-num">{{seckillCoupons[0]?.discountAmount || 0}}</text>%</text>
              </view>
              <text class="coupon-condition" v-if="seckillCoupons[0]?.minAmount">满{{seckillCoupons[0]?.minAmount}}元可用</text>
            </view>
            <view class="coupon-right">
              <view class="coupon-info">
                <text class="coupon-name">{{seckillCoupons[0]?.name || '优惠券抢购'}}</text>
                <text class="coupon-timer" v-if="countdown.hours !== undefined">
                  剩余 {{countdown.hours}}:{{countdown.minutes}}:{{countdown.seconds}}
                </text>
              </view>
              <view class="coupon-btn" @tap.stop="grabCoupon(seckillCoupons[0])">抢购</view>
            </view>
            <text class="coupon-more" @tap.stop="showCouponPopup">更多优惠</text>
          </view>
        </view>
      </view>

      <!-- 商品列表 -->
      <view class="products-section">
        <!-- 商品列表标题 -->
        <view class="section-header">
          <text class="section-title">{{ currentCategory ? currentCategoryName : '推荐商品' }}</text>
          <view class="sort-options">
            <text 
              class="sort-item" 
              :class="{ active: sortField === 'createTime' }"
              @tap="changeSort('createTime')"
            >最新</text>
            <text 
              class="sort-item" 
              :class="{ active: sortField === 'sales' }"
              @tap="changeSort('sales')"
            >销量</text>
          </view>
        </view>

        <!-- 商品网格 -->
        <view class="products-grid">
          <view 
            v-for="product in products" 
            :key="product.id" 
            class="product-card"
            @tap="goToDetail(product.id)"
          >
            <image :src="product.image || '/static/logo.png'" mode="aspectFill" class="product-image" />
            <view class="product-info">
              <text class="product-name">{{ product.name }}</text>
              <view class="product-meta">
                <text class="product-price">¥{{ product.minPrice }}</text>
                <text class="product-sales">已售{{ product.sales || 0 }}</text>
              </view>
              <view class="product-tags" v-if="product.description">
                <text>{{splitAndTruncate(product.description)}}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载状态 -->
        <view v-if="loading" class="loading">加载中...</view>
        <view v-if="!hasMore" class="no-more">没有更多了</view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { listCategoryVoByPageUsingPost } from '../../backend/categoryController';
import { listProductVoByPageUsingPost } from '../../backend/productController';
import { listSeckillCouponUsingGet } from '../../backend/couponController';
import { addUserCouponUsingPost } from '../../backend/userCouponController';
import type { API } from '../../backend/typings';
import { getBannersUsingGet } from '../../backend/carouselController';

// 状态管理
const loading = ref(false);
const refreshing = ref(false);
const hasMore = ref(true);
const currentCategory = ref<number>();
const currentCategoryName = ref('推荐商品');
const sortField = ref('createTime');
const sortOrder = ref('desc');
const products = ref<API.ProductVO[]>([]);
const categories = ref<API.CategoryVO[]>([]);
const bannerList = ref<API.CarouselVO[]>([]);
const searchKeyword = ref('');
const isSearchFocused = ref(false);
const seckillCoupons = ref<API.CouponVO[]>([]);
const showPopup = ref(false);
const hasLogin = ref(false);

// 查询参数
const queryParams = reactive({
  current: 1,
  pageSize: 10,
  name: '',
  sortField: 'createTime',
  sortOrder: 'desc',
  categoryId: undefined as number | undefined,
  status: 'active'
});

// 获取商品列表
const fetchProducts = async (refresh = false) => {
  if (loading.value) return;
  
  if (refresh) {
    queryParams.current = 1;
    hasMore.value = true;
    products.value = [];
  }

  if (!hasMore.value) return;
  loading.value = true;

  try {
    const params = {
      ...queryParams,
      name: searchKeyword.value
    };
    const res = await listProductVoByPageUsingPost(params);
    
    if (res?.code === 0 && res?.data) {
      const newProducts = res.data.records || [];
      const total = res.data.total || 0;
      
      products.value = refresh ? newProducts : [...products.value, ...newProducts];
      
      // 判断是否还有更多数据
      const currentTotal = queryParams.current * queryParams.pageSize;
      hasMore.value = currentTotal < total;
      
      // 如果当前页数据量小于pageSize，说明没有更多数据了
      if (newProducts.length < queryParams.pageSize) {
        hasMore.value = false;
      }
    } else {
      hasMore.value = false;
    }
  } catch (error) {
    console.error('获取商品列表失败：', error);
    uni.showToast({
      title: '获取商品列表失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    if (refresh) {
      uni.stopPullDownRefresh();
    }
  }
};

// 获取轮播图方法
const fetchBanners = async () => {
  try {
    const res = await getBannersUsingGet();
    if (res?.code === 0 && res.data) {
      bannerList.value = res.data.map(item => ({
        id: item.id,
        image: item.imageUrl // 注意字段映射
      }));
    }
  } catch (error) {
    console.error('获取轮播图失败:', error);
    uni.showToast({
      title: '轮播图加载失败',
      icon: 'none'
    });
  }
};


// 切换排序
const changeSort = (field: string) => {
  if (loading.value) return;
  if (sortField.value === field) {
    sortOrder.value = sortOrder.value === 'desc' ? 'asc' : 'desc';
  } else {
    sortField.value = field;
    sortOrder.value = 'desc';
  }
  queryParams.sortField = field;
  queryParams.sortOrder = sortOrder.value;
  fetchProducts(true);
};

//切割详情
const splitAndTruncate = (str: string): string => {
  const words = str.split('');
  if (words.length > 15) {
    return words.slice(0, 15).join('') + '...';
  }
  return str;
}

// 下拉刷新
const onRefresh = async () => {
  if (loading.value) return;
  refreshing.value = true;
  await fetchProducts(true);
  refreshing.value = false;
  await fetchSeckillCoupons
};

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    queryParams.current++;
    fetchProducts();
  }
};

// 新增搜索处理方法
const handleSearch = () => {
  const keyword = searchKeyword.value.trim();
  if (!keyword) {
    uni.showToast({ title: '请输入搜索内容', icon: 'none' });
    return;
  }
  
  searchKeyword.value = '';
  uni.navigateTo({
    url: `/pages/search/search?keyword=${encodeURIComponent(keyword)}`
  });
};

// 新增清除搜索
const clearSearch = () => {
  searchKeyword.value = '';
  fetchProducts(true);
};

// 跳转搜索页
const goToSearch = () => {
  uni.navigateTo({
    url: '/pages/search/search'
  });
};

// 跳转详情页
const goToDetail = (id?: number) => {
  if (!id) return;
  uni.navigateTo({
    url: `/pages/product/detail?id=${id}`
  });
};

// 检查登录状态
const checkLogin = () => {
  const token = uni.getStorageSync('token');
  hasLogin.value = !!token;
  return hasLogin.value;
};

// 获取秒杀优惠券
const fetchSeckillCoupons = async () => {
  if (!checkLogin()) return;
  
  try {
    const res = await listSeckillCouponUsingGet({
      current: 1,
      pageSize: 10
    });
    
    if (res.code === 0 && res.data) {
      seckillCoupons.value = res.data.records || [];
    }
  } catch (error) {
    console.error('获取秒杀优惠券失败:', error);
  }
};

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '无限期';
  
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 倒计时数据
const countdown = reactive({
  hours: 0,
  minutes: "00",
  seconds: "00"
});

// 为每个优惠券添加独立倒计时
const couponCountdowns = ref<Record<number, {hours: number, minutes: string, seconds: string}>>({});

// 计算倒计时
const calculateCountdown = () => {
  if (!seckillCoupons.value.length || !seckillCoupons.value[0].seckillEndTime) return;
  
  const endTime = new Date(seckillCoupons.value[0].seckillEndTime).getTime();
  const now = new Date().getTime();
  const diff = endTime - now;
  
  if (diff <= 0) {
    countdown.hours = 0;
    countdown.minutes = "00";
    countdown.seconds = "00";
    return;
  }
  
  countdown.hours = Math.floor(diff / (1000 * 60 * 60));
  countdown.minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0');
  countdown.seconds = Math.floor((diff % (1000 * 60)) / 1000).toString().padStart(2, '0');
  
  // 计算每个优惠券的倒计时
  seckillCoupons.value.forEach(coupon => {
    if (coupon.id && coupon.seckillEndTime) {
      const endTimeMs = new Date(coupon.seckillEndTime).getTime();
      const diffMs = endTimeMs - now;
      
      if (diffMs <= 0) {
        couponCountdowns.value[coupon.id] = {
          hours: 0,
          minutes: "00",
          seconds: "00"
        };
      } else {
        couponCountdowns.value[coupon.id] = {
          hours: Math.floor(diffMs / (1000 * 60 * 60)),
          minutes: Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0'),
          seconds: Math.floor((diffMs % (1000 * 60)) / 1000).toString().padStart(2, '0')
        };
      }
    }
  });
};

// 启动倒计时计时器
let countdownTimer: number;
const startCountdown = () => {
  if (countdownTimer) clearInterval(countdownTimer);
  calculateCountdown();
  countdownTimer = setInterval(() => {
    calculateCountdown();
  }, 1000);
};

// 显示优惠券弹窗
const showCouponPopup = () => {
  if (!checkLogin()) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/profile/profile'
      });
    }, 1500);
    return;
  }
  
  uni.navigateTo({
    url: '/pages/coupon/seckill'
  });
};

// 领取优惠券
const grabCoupon = async (coupon: API.CouponVO) => {
  if (!coupon.id) return;
  
  try {
    const res = await addUserCouponUsingPost({
      couponId: coupon.id
    });
    
    if (res.code === 0) {
      uni.showToast({
        title: '领取成功',
        icon: 'success'
      });
      
      // 抢购成功后刷新优惠券列表和页面
      await fetchSeckillCoupons();
      await fetchProducts(true);
    } else {
      uni.showToast({
        title: res.message || '领取失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('领取优惠券失败:', error);
    uni.showToast({
      title: '领取失败',
      icon: 'none'
    });
  }
};

// 初始化数据
const initData = () => {
  fetchProducts(true);
  fetchBanners();
  if (checkLogin()) {
    fetchSeckillCoupons().then(() => {
      if (seckillCoupons.value.length > 0) {
        startCountdown();
      }
    });
  }
};

// 页面加载时初始化
onMounted(() => {
  initData();
});

// 页面卸载时清理定时器
onBeforeUnmount(() => {
  if (countdownTimer) clearInterval(countdownTimer);
});

// 每次显示页面时刷新数据
onShow(() => {
  if (products.value.length > 0) {
    initData();
  }
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.content-scroll {
  height: 100vh;
}

.search-section {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 16px;
  background: linear-gradient(180deg, #ff5722 0%, #ff7043 100%);
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  height: 36px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 18px;
  padding: 0 16px;
}

.search-icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}

.search-input {
  flex: 1;
  padding: 0 8px;
  font-size: 14px;
  color: #333;
}

.clear-btn {
  font-size: 14px;
  color: #999;
  margin-left: 8px;
}

.search-btn {
  min-width: 60px;
  text-align: center;
  font-size: 14px;
  color: rgba(255,255,255,0.8);
  padding: 8px 12px;
  border-radius: 16px;
  transition: all 0.3s ease;
}

.search-btn.active {
  background: rgba(255,255,255,0.2);
  color: #fff;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

.banner {
  height: 180px;
  width: 100%;
}

.banner-image {
  width: 100%;
  height: 100%;
}

.products-section {
  padding-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #fff;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.sort-options {
  display: flex;
  gap: 16px;
}

.sort-item {
  font-size: 14px;
  color: #666;
}

.sort-item.active {
  color: #ff5722;
  font-weight: bold;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  padding: 12px;
}

.product-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 180px;
}

.product-info {
  padding: 12px;
}

.product-name {
  font-size: 14px;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 8px;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.product-price {
  font-size: 18px;
  font-weight: bold;
  color: #ff5722;
}

.product-sales {
  font-size: 12px;
  color: #999;
  background: #f8f8f8;
  padding: 2px 8px;
  border-radius: 10px;
}

.product-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.tag {
  font-size: 10px;
  color: #ff5722;
  background: #fff2ed;
  padding: 2px 6px;
  border-radius: 4px;
}

.loading, .no-more {
  text-align: center;
  padding: 16px;
  color: #999;
  font-size: 14px;
}

/* 修改搜索框获得焦点时的样式 */
.search-box:active,
.search-input:focus {
  transform: scale(1.02);
  box-shadow: 0 4rpx 20rpx rgba(255, 87, 34, 0.2);
}

/* 优惠券区域样式 */
.coupon-section {
  padding: 16rpx 24rpx;
  background: linear-gradient(to right, #ff9f43, #ff7043);
  margin: 12rpx 0;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 87, 34, 0.2);
  min-height: 120rpx;
  z-index: 1;
  position: relative;
}

.coupon-container {
  position: relative;
  width: 100%;
}

.compact-coupon-card {
  display: flex;
  width: 100%;
  height: 120rpx;
  border-radius: 12rpx;
  overflow: hidden;
  position: relative;
  background-color: rgba(255, 255, 255, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.3);
  padding: 0;
}

.fixed-bg {
  background-color: rgba(255, 87, 34, 0.15);
}

.percent-bg {
  background-color: rgba(33, 150, 243, 0.15);
}

.coupon-left {
  width: 200rpx;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 0 16rpx;
  position: relative;
  background-color: rgba(255, 255, 255, 0.1);
}

.coupon-left:after {
  content: '';
  position: absolute;
  right: 0;
  height: 80%;
  width: 2rpx;
  background: rgba(255,255,255,0.3);
}

.coupon-right {
  flex: 1;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding: 0 16rpx;
  height: 100%;
  position: relative;
}

.coupon-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 50%;
}

.coupon-amount {
  font-size: 24rpx;
  color: white;
  font-weight: bold;
  text-align: center;
}

.amount-num {
  font-size: 36rpx;
  font-weight: bold;
}

.coupon-condition {
  font-size: 20rpx;
  color: rgba(255,255,255,0.9);
  text-align: center;
  margin-top: 4rpx;
}

.coupon-name {
  font-size: 26rpx;
  color: white;
  font-weight: 500;
  padding-right: 12rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.coupon-timer {
  font-size: 20rpx;
  color: rgba(255,255,255,0.9);
  margin-top: 4rpx;
}

.coupon-btn {
  min-width: 80rpx;
  margin-right: 20px;
  height: 50rpx;
  line-height: 50rpx;
  background: rgba(255,255,255,0.5);
  border: 1px solid rgba(255,255,255,0.8);
  border-radius: 25rpx;
  font-size: 24rpx;
  font-weight: 500;
  color: white;
  text-align: center;
  position: absolute;
  right: 120rpx;
  top: 50%;
  transform: translateY(-50%);
  z-index: 3;
  box-shadow: 0 4rpx 8rpx rgba(0,0,0,0.15);
  transition: all 0.2s;
}

.coupon-btn:active {
  transform: translateY(-50%) scale(0.95);
  opacity: 0.9;
}

.coupon-more {
  min-width: 110rpx;
  padding: 0 12rpx;
  height: 42rpx;
  line-height: 42rpx;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  right: 10rpx;
  font-size: 22rpx;
  color: #ffffff;
  background-color: rgba(0, 0, 0, 0.4);
  border-radius: 21rpx;
  text-align: center;
  z-index: 2;
  white-space: nowrap;
  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.2);
  transition: all 0.2s;
}

.coupon-more:active {
  transform: translateY(-50%) scale(0.95);
  opacity: 0.9;
}
</style>
